package com.vertx.starter.mysql;

import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.mysqlclient.MySQLConnectOptions;
import io.vertx.mysqlclient.MySQLPool;
import io.vertx.sqlclient.PoolOptions;
import lombok.extern.log4j.Log4j2;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

@Log4j2
public class MysqlUtil {

    private final Vertx vertx;

    private final int poolSize;

    private final List<JsonObject> dateConfig;

    private List<MySQLPool> clients;

    public MysqlUtil(Vertx vertx, int poolSize, List<JsonObject> dateConfig) {
        this.vertx = vertx;
        this.poolSize = poolSize;
        this.dateConfig = dateConfig;
        initPool();
    }

    private void initPool() {
        clients = new ArrayList<>();
        for (JsonObject datasource : dateConfig) {
            for (int j = 0; j < poolSize; j++) {
                MySQLConnectOptions connectOptions = new MySQLConnectOptions().setPort(datasource.getInteger("port")).setHost(datasource.getString("url")).setDatabase(datasource.getString("database")).setUser(datasource.getString("user")).setPassword(datasource.getString("password")).setCharset("utf8").setCollation("utf8_general_ci").setReconnectAttempts(3).setReconnectInterval(1000);
                PoolOptions poolOptions = new PoolOptions().setMaxSize(datasource.getInteger("max_pool_size")).setIdleTimeout(datasource.getInteger("max_idle_time"));
                MySQLPool client = MySQLPool.pool(vertx, connectOptions, poolOptions);
                clients.add(client);
            }
        }
    }

    public MySQLPool getConfigClient() {
        return clients.get(ThreadLocalRandom.current().nextInt(clients.size()));
    }

    public void close() {
        for (MySQLPool client : clients) {
            client.close();
        }
        log.info("mysql 关闭连接池！");
    }
}
